package com.mcxx.modules.miniSalvation.fundpay.service.write;

import com.mcxx.convert.FundPayConvert;
import com.mcxx.modules.miniSalvation.fundpay.dao.write.FundpayExceptionWriteDao;
import com.mcxx.modules.miniSalvation.fundpay.dto.FundpayExceptionDTO;
import com.mcxx.modules.miniSalvation.fundpay.entity.FundpayExceptionEntity;
import com.mcxx.modules.miniSalvation.fundpay.entity.SingleFundPayMemberEntity;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundpayExceptionReadService;
import com.mcxx.modules.temporary.fundpay.entity.TmpFundPayFamilyEntity;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service("singleFundPayExceptionWriteService")
@TaTransactional
public class SingleFundPayExceptionWriteService extends BaseService {
    private static final Logger logger = LoggerFactory.getLogger(SingleFundPayExceptionWriteService.class);
    @Autowired
    public FundpayExceptionWriteDao fundpayExceptionWriteDao;
    @Autowired
    private FundpayExceptionReadService fundpayExceptionReadService;


    public int insert(FundpayExceptionEntity fundpayExceptionEntity) {
        return fundpayExceptionWriteDao.insert(fundpayExceptionEntity);
    }


    public int insertIgnoreNull(FundpayExceptionEntity fundpayExceptionEntity) {
        return fundpayExceptionWriteDao.insertIgnoreNull(fundpayExceptionEntity);
    }


    public int update(FundpayExceptionEntity fundpayExceptionEntity) {
        return fundpayExceptionWriteDao.update(fundpayExceptionEntity);
    }


    public int updateIgnoreNull(FundpayExceptionEntity fundpayExceptionEntity) {
        return fundpayExceptionWriteDao.updateIgnoreNull(fundpayExceptionEntity);
    }


    public int batchInsert(List<FundpayExceptionEntity> fundpayExceptionEntityList) {
        return fundpayExceptionWriteDao.batchInsert(fundpayExceptionEntityList);
    }


    public int confirmException(List<String> idList) {
        return fundpayExceptionWriteDao.confirmException(idList);
    }


    public boolean checkAndConfirmException(String fundpayId, String businessType) {
        List<String> exceptionIds = fundpayExceptionReadService.getExceptionIdByFundpayId(fundpayId);
        if (exceptionIds.size() == 0) {
            return false;
        }

        logger.info("检查名册异常数据证明材料和银行账号是否已经配置， 异常数量：{}", exceptionIds.size());
        List<String> exceptionConfirmIds = new ArrayList<>();
        List<FundpayExceptionDTO> exceptionByBankList = null;
        if (Constant.BusinessCode.LINSHI.equals(businessType)) {
            exceptionByBankList = fundpayExceptionReadService.getTempExceptionByIDAndFundpayId(fundpayId, exceptionIds);
        } else {
            exceptionByBankList = fundpayExceptionReadService.getExceptionByIDAndFundpayId(fundpayId, exceptionIds);
        }
        for (FundpayExceptionDTO dto : exceptionByBankList) {
            if (StringUtils.isNotEmpty(dto.getBankCode())
                    && StringUtils.isNotEmpty(dto.getBankAccount())
                    && StringUtils.isNotEmpty(dto.getBankCardImg())) {
                exceptionConfirmIds.add(dto.getId());
            }
        }
        if (exceptionConfirmIds.size() > 0) {
            int num = this.confirmException(exceptionConfirmIds);
            logger.info("确认名册异常数据，size={}", num);
        }

        exceptionIds = fundpayExceptionReadService.getExceptionIdByFundpayId(fundpayId);
        if (exceptionIds.size() > 0) {
            return true;
        }
        return false;
    }


    public int deleteByFundPayId(@Param("fundPayIdList") List<String> fundPayIdList) {
        return fundpayExceptionWriteDao.deleteByFundpayId(fundPayIdList);
    }


    public void checkSaveFundPayException(String fundPayId, Date payDate, List<SingleFundPayMemberEntity> fundPayFamilyList) {
        List<FundpayExceptionEntity> exceptionEntityList = new ArrayList<>();
        logger.info("检查发放名册家庭（当月新增）银行卡账号/银行卡复印件是否完整");
        List<String> fundPayIdList = new ArrayList<>();
        fundPayIdList.add(fundPayId);
        int count = this.deleteByFundPayId(fundPayIdList);
        logger.info("删除该名册({})下的所有异常数据：{}", fundPayId, count);
        for (SingleFundPayMemberEntity entity : fundPayFamilyList) {
            Date startDate = entity.getStartDate();
            if (DateUtil.inSameMonth(payDate, startDate)) {
                boolean hasException = false;
                String msg = "";
                if (StringUtils.isEmpty(entity.getBankCardImg())) {
                    hasException = true;
                    msg = "银行卡证明材料为空";
                }

                if (StringUtils.isEmpty(entity.getBankCode())) {
                    hasException = true;
                    msg += (StringUtils.isEmpty(msg) ? "" : "; ") + "银行编码为空";
                }

                if (StringUtils.isEmpty(entity.getBankAccount())) {
                    hasException = true;
                    msg += (StringUtils.isEmpty(msg) ? "" : "; ") + "银行卡账号为空";
                }
                if (hasException) {
                    logger.info("该对象({}/{})账号信息存在异常: {}", entity.getName(), entity.getIdcard(), msg);
                    FundpayExceptionEntity exceptionEntity = FundPayConvert.convertFundpayExceptionEntity(entity);
                    exceptionEntity.setFundpayId(fundPayId);
                    exceptionEntity.setExceptionDesc(msg);
                    exceptionEntity.setPayDate(payDate);
                    exceptionEntity.setExceptionType(Constant.FundpayException.E_TYPE_BANK);
                    exceptionEntityList.add(exceptionEntity);
                }
            }
        }
        if (exceptionEntityList.size() > 0) {
            this.batchInsert(exceptionEntityList);
            logger.info("批量插入名册异常数据, fundpayId={}, size={}", fundPayId, exceptionEntityList.size());
        }
    }



    public void checkSaveTempFundpayException(String fundpayId, Date payDate, List<TmpFundPayFamilyEntity> fundPayFamilyEntityList) {
        List<FundpayExceptionEntity> exceptionEntityList = new ArrayList<>();
        logger.info("检查发放名册家庭银行卡账号/银行卡复印件是否完整");
        List<String> fundpayIdList = new ArrayList<>();
        fundpayIdList.add(fundpayId);
        int count = this.deleteByFundPayId(fundpayIdList);
        logger.info("删除该名册({})下的所有异常数据：{}", fundpayId, count);
        for (TmpFundPayFamilyEntity entity : fundPayFamilyEntityList) {
            if (StringUtils.isEmpty(entity.getExtrOrderId())) {
                boolean hasException = false;
                String msg = "";
                if (StringUtils.isEmpty(entity.getBankCardImg())) {
                    hasException = true;
                    msg = "银行卡证明材料为空";
                }

                if (StringUtils.isEmpty(entity.getBankCode())) {
                    hasException = true;
                    msg += (StringUtils.isEmpty(msg) ? "" : "; ") + "银行编码为空";
                }

                if (StringUtils.isEmpty(entity.getBankAccount())) {
                    hasException = true;
                    msg += (StringUtils.isEmpty(msg) ? "" : "; ") + "银行卡账号为空";
                }
                if (hasException) {
                    FundpayExceptionEntity exceptionEntity = FundPayConvert.convertFundpayExceptionEntity(entity);
                    exceptionEntity.setFundpayId(fundpayId);
                    exceptionEntity.setExceptionDesc(msg);
                    exceptionEntity.setPayDate(payDate);
                    exceptionEntity.setExceptionType(Constant.FundpayException.E_TYPE_BANK);
                    exceptionEntityList.add(exceptionEntity);
                }
            }
        }
        if (exceptionEntityList.size() > 0) {
            this.batchInsert(exceptionEntityList);
            logger.info("批量插入名册异常数据, fundpayId={}, size={}", fundpayId, exceptionEntityList.size());
        }
    }


    public int deleteByFundpayId(@Param("fundpayIdList") List<String> fundpayIdList) {
        return fundpayExceptionWriteDao.deleteByFundpayId(fundpayIdList);
    }
}
